package dyy.zc.sportruler.ui.activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import dyy.zc.sportruler.R;
import dyy.zc.sportruler.application.MyApplication;
import dyy.zc.sportruler.base.BaseActivity;
import dyy.zc.sportruler.bean.PlanInfo;
import dyy.zc.sportruler.bean.SendPlan;
import dyy.zc.sportruler.bean.SportName;
import dyy.zc.sportruler.bean.StudentInfo;
import dyy.zc.sportruler.ui.adapter.MakePlanAdapter;
import dyy.zc.sportruler.utils.AppManager;
import dyy.zc.sportruler.utils.AproriUtils;
import dyy.zc.sportruler.utils.BmobUtils;
import dyy.zc.sportruler.utils.DataInfo;
import dyy.zc.sportruler.utils.MakePlanUtils;
import dyy.zc.sportruler.utils.StringUtils;
import dyy.zc.sportruler.utils.ToastUtils;
import dyy.zc.sportruler.views.CodePopWindows;
import dyy.zc.sportruler.views.MyAlertDialog;

/**
 * Created by Administrator on 2016/10/28.
 */
public class MakePlanActivity extends BaseActivity implements View.OnClickListener {
    private TextView title,ok;
    public RelativeLayout rl_warmUpView, rl_mainActionView, rl_relaxActionView;
    public TextView tv_warmUp, tv_mainAction, tv_relaxAction;
    public ImageView iv_warmUpAdd, iv_mainActionAdd, iv_relaxActionAdd;
    public ListView warmUpListView, mainActionListView, relaxActionListView;
    public List<SportName> warmUpList = new ArrayList<>();
    public List<SportName> mainActionList = new ArrayList<>();
    public List<SportName> relaxActionList = new ArrayList<>();
    //创建适配器
    public MakePlanAdapter warmUpAdapter;
    public MakePlanAdapter mainActionAdapter;
    public MakePlanAdapter relaxActionAdapter;
    private MakePlanUtils makePlanUtils;
    private CodePopWindows popWindows;
    private PlanInfo planInfo;
    private String result;
    private String Code;
    private BmobUtils bmobUtils;
    public StudentInfo studentInfo;
    public SendPlan sendPlan;
    @Override
    protected void findViewByIDS() {
        title = findViewsById(R.id.top_tv_title);
        ok = findViewsById(R.id.top_tv_right);
        rl_warmUpView = findViewsById(R.id.base_day_rl_warmUp);
        rl_mainActionView = findViewsById(R.id.base_day_rl_mainAction);
        rl_relaxActionView = findViewsById(R.id.base_day_rl_relaxAction);

        tv_warmUp = findViewsById(R.id.makePlan_tv_warmUp);
        iv_warmUpAdd = findViewsById(R.id.makePlan_iv_warmUpAdd);
        warmUpListView = findViewsById(R.id.makePlan_listView_warmUp);

        tv_mainAction = findViewsById(R.id.makePlan_tv_mainAction);
        iv_mainActionAdd = findViewsById(R.id.makePlan_iv_mainActionAdd);
        mainActionListView = findViewsById(R.id.makePlan_listView_mainAction);

        tv_relaxAction = findViewsById(R.id.makePlan_tv_relaxAction);
        iv_relaxActionAdd = findViewsById(R.id.makePlan_iv_relaxActionAdd);
        relaxActionListView = findViewsById(R.id.makePlan_listView_relaxAction);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_make_plan);
//        Log.e("onCreate","MakePlanActivity onCreate");
        initData();
        bind();
    }

    /**
     * 当界面显示的时候，判断这个界面是不是第一次显示
     * 是：说明是从选择体型界面跳转过来的，设置isFirst = false
     * 否：说明是从添加动作界面跳转过来的，执行getResult()将选择的健身动作设置在列表中
     */
    @Override
    protected void onResume() {
        super.onResume();
//        Log.e("onResume","MakePlanActivity onResume");
        if (!MakePlanUtils.isFirst) {
            makePlanUtils.getResult();
        }
        MakePlanUtils.isFirst = false;
    }

    private void bind() {
        findViewsById(R.id.top_rl_right).setOnClickListener(this);
        iv_warmUpAdd.setOnClickListener(MakePlanUtils.warmUpAddListener);
        iv_mainActionAdd.setOnClickListener(MakePlanUtils.mainActionAddListener);
        iv_relaxActionAdd.setOnClickListener(MakePlanUtils.relaxActionAddListener);
        warmUpListView.setOnItemClickListener(itemOnClickListener);

        popWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
    }

    private AdapterView.OnItemClickListener itemOnClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        }
    };


    private void initData() {
        dialog = ProgressDialog.show(this,null,"开始关联规则...");
        studentInfo = (StudentInfo) getIntent().getSerializableExtra("student");
        analyticalData(studentInfo);
        planInfo = new PlanInfo();
        sendPlan = new SendPlan();
        bmobUtils = new BmobUtils(this);
        title.setText("制定计划");
        popWindows = new CodePopWindows(this);
        ok.setTextColor(getResources().getColor(R.color.text_blue));
        ok.setText("发送");
        ok.setVisibility(View.VISIBLE);
        makePlanUtils = new MakePlanUtils(this);
        tv_warmUp.setText(R.string.warm_up);
        tv_mainAction.setText(R.string.main_action);
        tv_relaxAction.setText(R.string.relax_action);
        warmUpAdapter = new MakePlanAdapter(this, warmUpList);
        mainActionAdapter = new MakePlanAdapter(this, mainActionList);
        relaxActionAdapter = new MakePlanAdapter(this, relaxActionList);
        warmUpListView.setAdapter(warmUpAdapter);
        mainActionListView.setAdapter(mainActionAdapter);
        relaxActionListView.setAdapter(relaxActionAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_rl_right:
                nameDialog();
                break;
        }
    }

    private void savePlan(String result) {
        planInfo.setId(loginuser.getId());
        planInfo.setName(result);
        planInfo.setStudentName(studentInfo.getName());
//        Code = loginuser.getId()+"-"+result;
        planInfo.setMainList(mainActionList);
        planInfo.setWarmList(warmUpList);
        planInfo.setRelaxList(relaxActionList);
        bmobUtils.savePlan(planInfo,1,handler);
    }

    private BmobFile bmobFile;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1://保存计划成功
                    Bitmap image = CodeUtils.createImage(studentInfo.getId(), 150, 150,null);
                    if (image != null){
                        popWindows.setBitmap(image);
                        try {
                            bmobFile = new BmobFile(saveFile(image,"code.png"));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        bmobUtils.uploadCodeImg(bmobFile,3,4,handler);
                    }else {
                        dialog.dismiss();
                        ToastUtils.shortToast(MakePlanActivity.this,"二维码图片为空");
                    }
                    break;
                case 2://保存学员信息成功
                    sendPlan.setId(loginuser.getId());
                    sendPlan.setName(result);
                    sendPlan.setStudentName(studentInfo.getName());
                    bmobUtils.saveSendPlan(sendPlan,5,handler);
                    break;
                case 3://二维码图片上传成功
                    bmobUtils.saveStudentInfo(studentInfo,2,handler);
                    break;
                case 4://图片上传失败
                    dialog.dismiss();
                    ToastUtils.shortToast(MakePlanActivity.this,"网络错误，请稍后重试");
                    break;
                case 5://保存发送的计划成功
                    loginuser.setSend(loginuser.getSend()+1);
                    bmobUtils.updateInfo(loginuser,6,handler);
                    break;
                case 6://保存发送计划的数量
                    dialog.dismiss();
                    MyApplication.getInstance().saveUserInfo(loginuser);
                    // 设置背景颜色变暗
                    WindowManager.LayoutParams lp = getWindow().getAttributes();
                    lp.alpha = 0.5f;
                    getWindow().setAttributes(lp);
                    popWindows.setPlanName(result);
                    popWindows.initData();
                    popWindows.showAtLocation(findViewsById(R.id.makePlan), Gravity.CENTER,0,0);
                    break;
                case 777:
                    //显示关联动作
                    showAnalyticalDataWarmUp();
                    showAnalyticalDataMain();
                    showAnalyticalDataRelax();
                    if (DataInfo.warmupList.size()==0&&
                            DataInfo.mainList.size()==0&&
                            DataInfo.relaxList.size()==0){
                        ToastUtils.shortToast(MakePlanActivity.this,"暂无匹配数据");
                    }
                    dialog.dismiss();
                    break;
            }
        }
    };

    public void showAnalyticalDataWarmUp(){
        warmUpList.clear();
        warmUpList.addAll(DataInfo.warmupList);
        setListViewHeight(warmUpListView);
        warmUpAdapter.setList(warmUpList);
        warmUpListView.setVisibility(View.VISIBLE);
    }

    public void showAnalyticalDataMain(){
        mainActionList.clear();
        mainActionList.addAll(DataInfo.mainList);
        setListViewHeight(mainActionListView);
        mainActionAdapter.setList(mainActionList);
        mainActionListView.setVisibility(View.VISIBLE);
    }

    public void showAnalyticalDataRelax(){
        relaxActionList.clear();
        relaxActionList.addAll(DataInfo.relaxList);
        setListViewHeight(relaxActionListView);
        relaxActionAdapter.setList(relaxActionList);
        relaxActionListView.setVisibility(View.VISIBLE);
    }

    /**
     * 由于ScrollView中嵌套ListView显示的时候，高度只显示一行数据的高度
     * 所以应该计算ListView的原本高度，使用getCount()*item.getMeasuredHeight()
     * 计算高度，重新设置ListView的高度
     *
     * @param listView
     */
    public void setListViewHeight(ListView listView) {
        // 获取ListView对应的Adapter
        MakePlanAdapter adapter = (MakePlanAdapter) listView.getAdapter();
        if (adapter == null) {
            return;
        }
        int totalHeight = 0;
        int len = adapter.getCount();
        View item = adapter.getView(0, null, listView);
        item.measure(0, 0);
        totalHeight = item.getMeasuredHeight() * len;
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight;
        listView.setLayoutParams(params);
    }

    /**
     * 保存文件
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public File saveFile(Bitmap bm, String fileName) throws IOException {
        String path = Environment.getExternalStorageDirectory() +"/revoeye/";
        File dirFile = new File(path);
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
        return myCaptureFile;
    }

    /**
     * 名字提示框
     */
    private void nameDialog() {
        final MyAlertDialog logDialog = new MyAlertDialog(this);
        logDialog.builder()
                .setTitle("计划名称")
                .setEditTextHint("请输入计划名称")
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                })
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        result = logDialog.getResult();
                        if (StringUtils.isEmpty(result)){
                            ToastUtils.shortToast(MakePlanActivity.this,"名称不能为空");
                        }else {
                            dialog = ProgressDialog.show(MakePlanActivity.this,null,"正在保存计划......");
                            savePlan(result);
                        }

                    }
                })
                .show();
    }

    /**
     * 关联规则分析数据
     * @param studentInfo
     */
    private void analyticalData(final StudentInfo studentInfo) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                /**
                 * 筛选出相同的锻炼梦想的学员
                 */
                Iterator<StudentInfo> iterator = DataInfo.studentInfoList.iterator();
                while (iterator.hasNext()){
                    StudentInfo s = iterator.next();
                    if (!s.getWanted().equals(studentInfo.getWanted())){
                        iterator.remove();
                    }
                }
                /**
                 * 筛选出锻炼部位相同的学员
                 */
                Iterator<StudentInfo> it = DataInfo.studentInfoList.iterator();
                while (it.hasNext()){
                    StudentInfo s = it.next();
                    if (!s.getPart().equals(studentInfo.getPart())){
                        it.remove();
                    }
                }
                /**
                 * 筛选出大概范围之内的BMI的学员
                 */
                Iterator<StudentInfo> iterator1 = DataInfo.studentInfoList.iterator();
                while (iterator1.hasNext()){
                    StudentInfo s = iterator1.next();
                    double sBmi = Double.valueOf(s.getBmi());
                    double studentBmi = Double.valueOf(studentInfo.getBmi());
                    if (sBmi>=studentBmi){
                        if (studentBmi/sBmi < 0.8){
                            iterator1.remove();
                        }
                    }else {
                        if (sBmi/studentBmi < 0.8){
                            iterator1.remove();
                        }
                    }
                }
                /**
                 * 学员关联计划
                 */
                List<PlanInfo> planInfoList = new ArrayList<>();
                for (PlanInfo p:DataInfo.planInfoList){
                    for (StudentInfo s:DataInfo.studentInfoList){
                        if (p.getStudentName().equals(s.getName())){
                            planInfoList.add(p);
                            break;
                        }
                    }
                }
                DataInfo.planInfoList.clear();
                DataInfo.planInfoList.addAll(planInfoList);
                /**
                 * 初始化数据
                 */
                List<List<SportName>> reshenList = new ArrayList<>();
                List<List<SportName>> mainList = new ArrayList<>();
                List<List<SportName>> relaxList = new ArrayList<>();
                for (PlanInfo p:DataInfo.planInfoList){
                    reshenList.add(p.getWarmList());
                    mainList.add(p.getMainList());
                    relaxList.add(p.getRelaxList());
                }
                /**
                 * 开始算法计算 关联动作  热身
                 */
                if (reshenList.size()!=0){
                    DataInfo.warmupList.clear();
                    DataInfo.warmupList.addAll(analytical(reshenList));
                }

                /**
                 * 开始算法计算 关联动作  具体
                 */
                if (mainList.size()!=0){
                    DataInfo.mainList.clear();
                    DataInfo.mainList.addAll(analytical(mainList));
                }

                /**
                 * 开始算法计算 关联动作  放松
                 */
                if (relaxList.size() != 0){
                    DataInfo.relaxList.clear();
                    DataInfo.relaxList.addAll(analytical(relaxList));
                }

                handler.sendEmptyMessage(777);
            }
        }).start();
    }

    /**
     * 分析数据
     * @param analyticalList
     * @return
     */
    public List<SportName> analytical(List<List<SportName>> analyticalList){
        DataInfo.zhichi.clear();
        DataInfo.zixin.clear();
        DataInfo.analyticalList.clear();
        /**
         * 开始关联规则
         */
        AproriUtils.setRecord(analyticalList);
        AproriUtils.start();
        double maxZhiChi = 0;//支持度最大值
        double maxZixin = 0;//置信度最大值
        int maxIndex = 0;//最大值的坐标
        List<List<SportName>> tempList = new ArrayList<>();
        List<String> tempzxin = new ArrayList<>();
        List<String> tempzhichi = new ArrayList<>();
        /**
         * 筛选置信度最高的
         */
        for (int i = 0;i<DataInfo.zixin.size();i++){
            for (int j = 0;j<DataInfo.zixin.get(i).size();j++){
                if (maxZixin < Double.valueOf(DataInfo.zixin.get(i).get(j))){
                    maxZixin = Double.valueOf(DataInfo.zixin.get(i).get(j));
                    maxIndex = j;
                }
            }
            tempList.add(DataInfo.analyticalList.get(i).get(maxIndex));
            tempzxin.add(DataInfo.zixin.get(i).get(maxIndex));
            tempzhichi.add(DataInfo.zhichi.get(i).get(maxIndex));
        }
        maxIndex = 0;//最大值的坐标
        /**
         * 筛选支持度最高的
         */
        for (int i = 0;i<tempzhichi.size();i++) {
            if (maxZhiChi < Double.valueOf(tempzhichi.get(i))){
                maxZhiChi = Double.valueOf(tempzhichi.get(i));
                maxIndex = i;
            }
        }
        //最后结果的动作
        if (tempList.size()==0){
            return new ArrayList<>();
        }
        return  tempList.get(maxIndex);
    }
}
